//引入公共方法
const Common = require('./common')
//引入表对应的实体模型
const UserModel = require('../models/user')
//引入常量模块
const Constant = require('../constant/constant')
//引入日期格式化模块
const dateFormat = require('dateformat')
//require('../utils/jwt') === exports
const { JWT } = require('../utils/jwt')
const { getParams } = require('../utils/getParams')

//配置对象
let exportObject = { login }
module.exports = exportObject
//1、获得活动列表的函数
function login(req, res) {
  //1、先获得一个返回的对象
  let resObj = Common.clone(Constant.DEFAULT_SUCCESS)
  let params = getParams(req)
  console.log(params)
  if (!params) {
    console.log('没有参数')
  }
  //2、启动一个异步的任务对象
  let tasks = {
    //2.1 校验参数
    checkParams(cb) {
      Common.checkParams(params, ['name', 'pass'], cb)
    },
    //2.2 执行查询操作
    query: [
      'checkParams',
      (result, cb) => {
        UserModel.findOne({
          where: {
            name: params.name,
            pass: params.pass,
          },
        })
          .then(function (v) {
            console.log(v)
            let obj = null
            if (v) {
              obj = {
                id: v.id,
                name: v.name,
                pass: v.pass,
                tel: v.tel,
                email: v.email,
                address: v.address,
                createdAt: dateFormat(v.createdAt, 'yyyy-mm-dd HH:MM:ss'),
                updatedAt: dateFormat(v.updatedAt, 'yyyy-mm-dd HH:MM:ss'),
              }
              resObj.data = { user: obj }
              resObj.code = 200
              resObj.msg = '登录成功'
              resObj.token = new JWT().sign(v.id, 86400)
            } else {
              resObj.data = { user: obj }
              resObj.code = 204
              resObj.msg = '请输入正确的用户名或密码'
            }
            //放行函数
            cb(null)
          })
          .catch(function (err) {
            console.log(err)
            //返回错误信息到async方法中
            cb(Constant.DEFAULT_ERROR)
          })
      },
    ],
  }
  //3、调用统一返回函数
  Common.autoFn(tasks, res, resObj)
}
